<?php

namespace App\Services\Spider;

use App\Console\Commands\TestQueue;
use App\Console\Commands\XgSpiderComm;
use EasyWeChat\Kernel\Support\File;
use QL\QueryList;
use GuzzleHttp\Client;

/*
相关的：https://app.wuzhuiso.com/v1/pc/suggest?callback=suggest_so&encodein=utf-8&encodeout=utf-8&count=20&sl=20&format=json&src=srp_suggst&fields=word&word=%E7%A4%BE%E4%BF%9D&pq=&llbq=A5%2CB5%2CC5%2CD5&cache=&id=&t=1695615872650

*/

class WuzhuisoDrive extends God
{
    private $ipArray=[];
    protected $keyword = '';

    function claws(string $keyword)
    {
        $this->keyword = $keyword;

        for ($pn=1;$pn<=3;$pn++) {
            $api = 'https://www.wuzhuiso.com/s?q=' . urlencode($keyword) . '&fr=none&a=wenda&filt=&adv_t=&pn=' . $pn;
            $this->get_aysncpage($api,$pn);  //异步
        }
    }


    // 关联词
    protected function relevance($keyword) {

        $pn = 1;
        $relevance['title'] = [];
        while (true) {
            $api = 'https://www.wuzhuiso.com/s?q=' . urlencode($keyword) . '&src=srp&fr=none&a=www&pn=' . $pn;
            $html = $this->get_page($api);
            if ($html == false) return null;

            $ql = QueryList::html($html)->removeHead();
            // $ql_titles = $ql->find('.res-list');
            // if (!$ql_titles) {
            //     return null;
            // }
            $title =  $ql->find('div.relation>ul>li>a')->texts()->all();

            $relevance['title'] = array_merge($title, $relevance['title']);
            if (!$title ) {
                return null;
            }
            if (count($title ) < 10) {
                $pn++;
                continue;
            } else {
                break;
            }
        }
        if (count($relevance['title'])>15) {
            //取15个数组
            $relevance['title'] = array_slice($relevance['title'], 0, 15);

        }
        return $relevance['title'];
    }


//    protected function relevanceImg($keyword) {
//            //下面是js，取不了
//            $api = 'https://www.wuzhuiso.com/s?q='.urlencode($keyword).'&src=srp&fr=none&a=image';
//            $html = $this->get_page($api);
//            if ($html == false) return null;
//
//            $ql = QueryList::html($html)->removeHead();
//
//            $img = $ql->find('img')->attr('src');
//
//            dd("100>>>>",$img);
//
//    }

    private function get_ipjson_array() {
        $url = 'http://gev.qydailiip.com/api/?apikey=977e3d0aa43582bc0ecabccecdd1c26d0b34fe3d&num=60&type=json&line=win&proxy_type=secret&end_time=0';
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 1000,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        $pattern = '/ERROR/';
        if (preg_match($pattern, $response)) {
            return false;
        } else {
            $arr = json_decode($response, true);
            foreach ($arr as $item) {
                $this->ipArray[] = $item;
            }
        }

    }

    function get_ipaddress() {
        $i = 0;
        while ($i < 3) {
            $i++;
            if (count($this->ipArray) < 10) {
                  sleep(5);
                  $this->get_ipjson_array();
            }
            if (count($this->ipArray) > 1) {
                return array_pop($this->ipArray);
            }
        }
    }


    protected function get_aysncpage($api,$pn)
    {
        try {
            $ip = $this->get_ipaddress();
            $client = new \GuzzleHttp\Client(['verify' => false,'timeout'=>1000,'proxy' => 'http://'.$ip]);
            $response = new \GuzzleHttp\Psr7\Request('get',$api);
            $promise = $client->sendAsync($response)->then(function ($resp) use($pn) {
                $status = $resp->getStatusCode();
                if ($status == 200 && $resp->getBody()) {
                    self::parase_content($resp->getBody(),$this->keyword,$pn);
                }
            });
           $promise->wait();
        }catch (\Exception $e) {
            return Null;
        }

    }

    protected static function parase_content($body,$keyword,$pn) {
        $ql = QueryList::html($body)->removeHead();
        $ql_titles = $ql->find('.res-list');
        if (!$ql_titles) {
            return null;
        }
        $res['title'] =  $ql->find('.res-list>h3.res-title>a')->attrs('title')->all();
        $res['desc'] = $ql_titles->find('p.res-desc')->texts()->all();
        if (!$res['title'] || !$res['desc']) {
            return null;
        }
        echo PHP_EOL."找到内容页面{$pn}   ";
        foreach($res['title'] as $k=>$v) {
            $newSpirder[] = [
                'title' => $res['title'][$k],
                'short_article' => $res['desc'][$k]
            ];
        }
        shuffle($newSpirder);
        XgSpiderComm::CallSpiderResult($newSpirder,$keyword,$pn);

    }

}
